//
//  M4FourInfoViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/14.
//

import UIKit

class M4FourInfoViewController: M4BaseViewController {
    
    @IBOutlet weak var M4FourInfoTypeButton1: UIButton!
    
    @IBOutlet weak var M4FourInfoTypeButton2: UIButton!
    
    @IBOutlet weak var M4FourInfoNameView: UIView!
    
    @IBOutlet weak var M4FourInfoNameTF: UITextField!
    
    @IBOutlet weak var M4FourInfoNumberView: UIView!
    
    @IBOutlet weak var M4FourInfoNumberTF: UITextField!
    
    @IBOutlet weak var M4FourInfoSubmitButton: UIButton!
    
    
    @IBOutlet weak var M4DecriptionView: M4DecriptionStringView!
    private var m4enterTime: Int = 0
    
    var isInfoPage: Bool = true
    
    private var selectedType: String = "3"
    var cardNumberData: (String, Int, Int) = ("", 0, 0)
    var GASQ = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        
        M4DecriptionView.c = self
        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Tarjeta bancaria", M4NavTitleColor: COLOR_333333)
        M4FourInfoNameView.layer.borderColor = COLOR_CCCCCC.cgColor
        M4FourInfoNameView.layer.borderWidth = 0.5
        M4FourInfoNameView.layer.cornerRadius = 2
        M4FourInfoNameView.layer.masksToBounds = true
        M4FourInfoNumberView.layer.borderColor = COLOR_CCCCCC.cgColor
        M4FourInfoNumberView.layer.borderWidth = 0.5
        M4FourInfoNumberView.layer.cornerRadius = 2
        M4FourInfoNumberView.layer.masksToBounds = true
        M4FourInfoSubmitButton.layer.cornerRadius = 2
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), .foregroundColor: COLOR_999999]
        M4FourInfoNameTF.attributedPlaceholder = NSAttributedString(string: "Seleccione", attributes: attributes)
        M4FourInfoNumberTF.attributedPlaceholder = NSAttributedString(string: "Por favor, complete el campo", attributes: attributes)
        M4FourInfoNumberTF.delegate = self
        M4FourInfoNumberTF.keyboardType = .numberPad
        M4TypeButtonUIChange(selected: true, button: M4FourInfoTypeButton1)
        selectedType = "3"
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = .white
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        if isInfoPage {
            M4InfosPageBack()
        }
        else {
            self.navigationController?.popViewController(animated: true)
        }
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4FourInfoTypeChange(_ sender: UIButton) {
        if selectedType == "3" && sender == M4FourInfoTypeButton2 || selectedType == "40" && sender == M4FourInfoTypeButton1 {
            M4FourInfoNumberTF.text = ""
        }
        if sender == M4FourInfoTypeButton1 {
            M4TypeButtonUIChange(selected: true, button: M4FourInfoTypeButton1)
            M4TypeButtonUIChange(selected: false, button: M4FourInfoTypeButton2)
            selectedType = "3"
        }
        else {
            M4TypeButtonUIChange(selected: true, button: M4FourInfoTypeButton2)
            M4TypeButtonUIChange(selected: false, button: M4FourInfoTypeButton1)
            selectedType = "40"
        }
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4FourInfoToBankList(_ sender: UIButton) {
        let page = M4BankNameListViewController()
        page.M4BankNameSelectBlock = { name in
            self.M4FourInfoNameTF.text = name
        }
        self.navigationController?.pushViewController(page, animated: true)
        sender.M4EventUnavailable = false
    }
    
    
    @IBAction func M4FourInfoSubmitClick(_ sender: UIButton) {
        view.endEditing(true)
        var isReturn: Bool = false
        let numberCount = selectedType == "3" ? 16 : 18
        let cardNumber = M4FourInfoNumberTF.text?.replacingOccurrences(of: " ", with: "") ?? ""
        if M4FourInfoNameTF.text?.count == 0 {
            self.view.makeToast("Seleccione el nombre del banco", position: .center)
            isReturn = true
        }
        else if M4FourInfoNumberTF.text?.count == 0 {
            self.view.makeToast("Ingrese el número de cuenta bancaria correcto", position: .center)
            isReturn = true
        }
        else if cardNumber.count != numberCount {
            self.view.makeToast("El formato de su cuenta bancaria puede ser incorrecto, verifique detenidamente. No podemos transferir fondos a una cuenta bancaria incorrecta", position: .center)
            isReturn = true
        }
        if isReturn {
            sender.M4EventUnavailable = false
            return
        }
        let alert = UINib(nibName: "M4BankInfoConfirmView", bundle: nil).instantiate(withOwner: self).last as! M4BankInfoConfirmView
        alert.M4BankInfoUpdate(name: M4FourInfoNameTF.text ?? "", type: selectedType == "3" ? "Tarjeta de débito" : "CLABE", number: M4FourInfoNumberTF.text ?? "")
        alert.M4BankInfoConfirmBlock = {
            self.M4SubmitFourInfoNet(cardNo: cardNumber)
        }
        self.view.addSubview(alert)
        alert.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
            alert.alpha = 1
            alert.transform = CGAffineTransform.identity
        }
        alert.M4DecriptionView.c = self
//        alert.M4AlertViewShow()
        sender.M4EventUnavailable = false
    }
    
}

extension M4FourInfoViewController {
    
    private func M4SubmitFourInfoNet(cardNo: String) {
        let m4endTime = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        let param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 5, "ZOnKyB": m4endTime , "PgjQFUwCJu": M4FourInfoNameTF.text ?? "", "PUsNSIIKP": cardNo, "KfKTSxqHh": selectedType]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.M4FourInfoSubmitButton.M4EventUnavailable = false
            if model.code == 1 {
                if !self.isInfoPage {
                    self.navigationController?.viewControllers.removeAll(where: {$0 is M4BankVerficationViewController})
                    self.navigationController?.popViewController(animated: true)
                }
                else {
                    let vc = M4FiveInfosViewController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
                self.uploadData()
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    
    
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 5001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "akgjrt" : cardNumberData.2 - cardNumberData.1,
                "fqwqwe" : cardNumberData.0,
                "GASQ" : GASQ
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .BankCard, paramsKey: "aASRW", params: params, complete: nil)
    }
}

extension M4FourInfoViewController: UITextFieldDelegate {
    
    private func M4TypeButtonUIChange(selected: Bool, button: UIButton) {
        button.setTitleColor(selected ? COLOR_00479D : COLOR_666666, for: .normal)
        button.titleLabel?.font = selected ? UIFont.systemFont(ofSize: 14, weight: .bold) : UIFont.systemFont(ofSize: 14, weight: .regular)
        button.setBackgroundImage(UIImage(named: selected ? "info_icon_choose_pre" : "info_icon_choose"), for: .normal)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text
//        let newStr = (oldStr as NSString?)?.replacingCharacters(in: range, with: string)
        // 只能输入数字
        let characterSet = NSCharacterSet.init(charactersIn: "0123456789")
        let tempString = string.replacingOccurrences(of: " ", with: "")
        if (tempString.rangeOfCharacter(from: characterSet.inverted) != nil) {
            return false
        }
        var text = ((oldStr as NSString?)?.replacingCharacters(in: range, with: string))!
        text = text.replacingOccurrences(of: " ", with: "")
        var newString = ""
        while text.count > 0 {
            let subString = (text as NSString).substring(to: min(text.count, 4))
            newString = newString.appending(subString)
            if subString.count == 4 {
                newString = newString.appending(" ")
            }
            text = (text as NSString).substring(from: min(text.count, 4))
        }
        newString = newString.trimmingCharacters(in: characterSet.inverted)
        let count1 = selectedType == "3" ? 20 : 22
        if newString.count > count1 {
            return false
        }
        if range.location != textField.text?.count {
            textField.text = newString
            return false
        }
        textField.text = newString
        return false
    }
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == M4FourInfoNumberTF{
            cardNumberData.1 = Int(Date().timeIntervalSince1970 * 1000)
            
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == M4FourInfoNumberTF{
        cardNumberData.2 = Int(Date().timeIntervalSince1970 * 1000)
        }
        cardNumberData.0 = textField.text ?? ""
    }
}
